package com.hp.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hp.context.Config;
import com.hp.dao.RoleDao;
import com.hp.entity.Role;
import com.hp.result.DataGridResultInfo;
import com.hp.result.ResultUtil;
import com.hp.result.SubmitResultInfo;
import com.hp.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Transactional(readOnly = true)
    @Override
    public DataGridResultInfo page(int page, int rows) {
        Page<Role> startPage = PageHelper.startPage(page, rows);//使用分页插件方法
        roleDao.findAll();//插件方法必须在查询数据之前
        //封装数据
        DataGridResultInfo dataGridResultInfo = new DataGridResultInfo();
        dataGridResultInfo.setRows(startPage.getResult());//当前查询的数据
        dataGridResultInfo.setTotal((int) startPage.getTotal());//总页数
        return dataGridResultInfo;
    }

    @Override
    public SubmitResultInfo addRole(Role role) {
       Role r= roleDao.findByRoleName(role.getRolename());
       if(r!=null){//已经有的
           return ResultUtil.createSubmitResult(ResultUtil.createFail(Config.MESSAGE, 669, new Object[]{"角色"}));
       }
        roleDao.addRole(role);
        return ResultUtil.createSubmitResult(ResultUtil.createSuccess(Config.MESSAGE, 661, new Object[]{"角色"}));

    }

    @Transactional(readOnly = true)
    @Override
    public Role findById(int id) {
        return roleDao.findById(id);
    }

    @Override
    public SubmitResultInfo updateRole(Role role) {
        Role r= roleDao.findByRoleName(role.getRolename());
        if(r!=null){//已经有的
            return ResultUtil.createSubmitResult(ResultUtil.createFail(Config.MESSAGE, 669, new Object[]{"角色"}));
        }
        roleDao.update(role);
        return ResultUtil.createSubmitResult(ResultUtil.createSuccess(Config.MESSAGE, 661, new Object[]{"角色"}));

    }
    @Transactional(readOnly = true)
    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }
}
